<?php

declare(strict_types=1);

namespace App\Controller\Api;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\AutoController;
use App\Model\Order as ModelOrder;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\UserMiddleware;
use App\Model\Cart;
use App\Model\Good;
use App\Model\OrderGood;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use App\JsonRpc\PayLogService;

/**
 * @AutoController(prefix="/api/order")
 */
class Order extends AbstractController
{
    /**
     * @Middlewares({
     *     @Middleware(UserMiddleware::class)
     * })
     */
    public function list() {
        $data = $this->request->all();
        $query = ModelOrder::query();

        $query = $query->with('goods');
        $query = $query->where('user_id', $this->request->getHeader('uuid')[0]);

        $query = $query->orderBy('id', 'desc');

        if (isset($data['page_size']) && $data['page_size'] <= 0) {
            $list = $query->get();
        }else{
            $list = $query->paginate($data['page_size'] ?? 20);
        }
        
        // 假设在另一个服务器记录支付回调记录，然后此处调用另一台服务器的数据来显示

        // 此处筛选未支付的订单进行查询，然后查询到支付成功的订单进一步update成已支付的状态
        $orderNoArray = $list->where('status', 0)->pluck('order_no')->toArray(); // pluck相当于进阶版的tp->column('')
        // var_dump($orderNoArray);

        try {
            // rpc调用查询支付结果
            $client = ApplicationContext::getContainer()->get(PayLogService::class);
            $orderPayLogs = $client->getByOrderNo($orderNoArray);
        }catch(\Exception $e) {
            print_r($e->getMessage());
        }
        
        // 遍历此次订单查询的列表，给每个订单加上支付的状态显示
        foreach ($list as $item) {
            $item->status_text = '未知';

            if ($item->status == 0) {
                if (!empty($orderPayLogs)) {
                    $item->status_text = '未支付';
                    if (!empty($orderPayLogs[$item->order_no])) {
                        $item->status_text = '已支付';
                        $item->status = 1;
                        $item->pay_time = strtotime($orderPayLogs[$item->order_no]['create_time']);
                        $item->transaction_id = $orderPayLogs[$item->order_no]['transaction_id'];
    
                        // 查询到支付记录，更新到本服务器的数据库
                        ModelOrder::where('id', $item->id)->update([
                            'status' => 1,
                            'pay_time' => $item->pay_time,
                            'transaction_id' => $item->transaction_id,
                        ]);
                    }
                }
            }else if ($item->status == 1) {
                $item->status_text = '已支付';
            }
            
        }

        return $this->success($list);
    }

    /**
     * @Middlewares({
     *     @Middleware(UserMiddleware::class)
     * })
     */
    public function preOrder() {
        $this->validate([
            'cart_ids' => 'required|array'
        ]);
        $data = $this->request->all();
        $uuid = $this->request->getHeader('uuid')[0];

        $cartList = Cart::query()
            ->with('good')
            ->whereIn('id', $data['cart_ids'])
            ->where('user_id', $uuid)
            ->get();
        
        $totalPrice = 0;
        foreach ($cartList as $cart) {
            // var_dump($cart);
            $good = Good::where('id', $cart->good_id)->where('status', 1)->first();
            if ($good == null) {
                $this->error('存在已失效的商品，请检查后再下单');
            }
            $totalPrice += round($good->single_price * $cart->amount, 2);
        }

        return $this->success([
            'cart' => $cartList,
            'total_price' => $totalPrice,
        ]);
    }

    /**
     * @Middlewares({
     *     @Middleware(UserMiddleware::class)
     * })
     */
    public function addOrder() {
        $this->validate([
            'cart_ids' => 'required|array'
        ]);
        $data = $this->request->all();
        $uuid = $this->request->getHeader('uuid')[0];

        $cartList = Cart::query()
            ->whereIn('id', $data['cart_ids'])
            ->where('user_id', $uuid)
            ->get();

        
        $totalPrice = 0;
        $orderGoods = [];
        foreach ($cartList as $cart) {
            // var_dump($cart);
            $good = Good::where('id', $cart->good_id)->where('status', 1)->first();
            if ($good == null) {
                return $this->error('存在已失效的商品，请检查后再下单');
            }
            $goodTotal = round($good->single_price * $cart->amount, 2);
            $totalPrice += $goodTotal;

            $og = new OrderGood();
            $og->good_id = $good->id;
            $og->good_title = $good->title;
            $og->single_price = $good->single_price;
            $og->amount = $cart->amount;
            $og->total_price = $goodTotal;
            $orderGoods[] = $og;
        }

        if (empty($orderGoods)) {
            return $this->error('无效的购物车id');
        }

        Db::beginTransaction();
        try {
            $order = new ModelOrder();
            $order->order_no = date('ymdHis').str_pad(strval(mt_rand(0,999999)), 6, '0', STR_PAD_LEFT);
            $order->user_id = $uuid;
            $order->total_price = $totalPrice;
            if (!$order->save()) {
                Db::rollBack();
                return $this->error();
            }

            foreach ($orderGoods as $good) {
                $good->order_id = $order->id;
                if (!$good->save()) {
                    Db::rollBack();
                    return $this->error();
                }
            }

            Cart::whereIn('id', $data['cart_ids'])->delete();
            
            Db::commit();

            return $this->success($order);
        }catch(\Exception $e){
            Db::rollBack();
            return $this->error($e->getMessage());
        }
        
    }
}
